package com.vgooo.client.ui;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;
import com.vgooo.bean.Brand;
import com.vgooo.bean.NewListInfo;
import com.vgooo.client.Main;
import com.vgooo.client.R;
import com.vgooo.client.ViewLayout;
import com.vgooo.client.ui.PullDownView.OnPullDownListener;
import com.vgooo.client.vchannel.VChannelFragmentActivity;
import com.vgooo.client.vchannel.news.NewsAdapter;
import com.vgooo.util.BitmapUtils;
import com.vgooo.util.DebugTools;
import com.vgooo.util.GSonTools;
import com.vgooo.util.HttpUtils;
import com.vgooo.util.JsonParserUtils;
import com.vgooo.util.TimeUtils;
import com.vgooo.util.Utils;

public final class VChannelFragment extends Fragment implements
		OnItemClickListener {

	private static final String KEY_CONTENT = "VChannelFragment:Content";

	private Brand brand;
	private NewsAdapter adapter;
	private List<NewListInfo> news;// 热门推荐手机列表
	private VChannelFragmentActivity context;
	private View view;

	private TextView footLoadingseeMore;// 加载更多
	private ProgressBar footLoadingProgressBar;// 进度条
	private View footView;// 底部加载更多

	private PullDownView mPullDownView;// 上拉显示更多，下拉更新控件
	private OnPullDownListener onPullDownListener;// 监听上拉显示更多，下拉更新控件
	private ListView videsList;// 视频信息列表显示控件

	private boolean isFirst = true;
	private int currentPage = 0;// 现在所在的页
	private boolean isRefresh = false;
	private int per = 30;

	private View processBar;

	private String time = TimeUtils.getSystemtTimeP();

	private static Map<String, Map<String, Object>> fragmentDatas = new HashMap<String, Map<String, Object>>();
	private static Map<String, List<NewListInfo>> newsCache = new HashMap<String, List<NewListInfo>>();
	private static Map<String, Object> fragmentCache = new HashMap<String, Object>();

	public static VChannelFragment newInstance(Brand brand,
			List<NewListInfo> news, VChannelFragmentActivity context) {

		if (fragmentCache.get(brand.brand_name) == null) {

			HashMap<String, Object> fragmentItem = new HashMap<String, Object>();
			fragmentItem.put("brand", brand);
			fragmentItem.put("news", news);
			fragmentItem.put("context", context);

			fragmentDatas.put(brand.brand_name, fragmentItem);

			VChannelFragment fragment = new VChannelFragment(brand, news,
					context);
			Bundle bundle = new Bundle();
			bundle.putString(KEY_CONTENT, brand.brand_name);
			fragment.setArguments(bundle);

			fragmentCache.put(brand.brand_name, fragment);
		}

		return (VChannelFragment) fragmentCache.get(brand.brand_name);

	}

	public VChannelFragment(Brand brand, List<NewListInfo> news,
			VChannelFragmentActivity context) {
		this.brand = brand;
		this.news = news;
		this.context = context;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		currentPage = 0;
		if (getArguments() != null) {
			String brand_name = getArguments().getString(KEY_CONTENT);

			HashMap<String, Object> map = (HashMap<String, Object>) fragmentDatas
					.get(brand_name);
			this.brand = (Brand) map.get("brand");
			this.news = (List<NewListInfo>) map.get("news");
			this.context = (VChannelFragmentActivity) map.get("context");
		}
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// 友盟统计功能，打开页面
		MobclickAgent.onResume(getActivity());
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPause(getActivity());
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		outState.putString(KEY_CONTENT, brand.brand_name);
	}
	
	

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewCreated(view, savedInstanceState);
	}

	public VChannelFragment() {
		super();
		// TODO Auto-generated constructor stub
	}

	@SuppressWarnings("unused")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		view = inflater.inflate(R.layout.v_channel_fragment, null);
		processBar = view.findViewById(R.id.loading_image);
		processBar.setVisibility(View.VISIBLE);

		mPullDownView = (PullDownView) view
				.findViewById(R.id.v_channel_PullDownView);
		videsList = mPullDownView.getListView();
		// 诉它数据加载完毕;
		mPullDownView.notifyDidLoad();

		footView = inflater.inflate(R.layout.listview_foot, null);
		footLoadingseeMore = (TextView) footView
				.findViewById(R.id.listview_foot_seee_more);
		footLoadingProgressBar = (ProgressBar) footView
				.findViewById(R.id.listview_foot_progressBar);
		footLoadingProgressBar.setVisibility(View.INVISIBLE);

		adapter = new NewsAdapter(news, context);

		videsList.addFooterView(footView);
		videsList.setFadingEdgeLength(0);

		videsList.setAdapter(adapter);
		mPullDownView.enableAutoFetchMore(true, 1);
		// 诉它数据加载完毕;
		mPullDownView.notifyDidLoad();
		// 告诉它获取更多完毕

		currentPage++;

		isFirst = true;

		footLoadingProgressBar.setVisibility(View.INVISIBLE);
		footLoadingseeMore.setText("查看更多");

		videsList.setOnItemClickListener(this);

		onPullDownListener = new OnPullDownListener() {

			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				currentPage = 1;
				isRefresh = true;

				new DownLaodData().execute("");
			}

			@Override
			public void onMore() {
				// TODO Auto-generated method stub
				footLoadingProgressBar.setVisibility(View.VISIBLE);
				footLoadingseeMore.setText("加载中..");
				isRefresh = false;

				new DownLaodData().execute("");
			}
		};
		mPullDownView.setOnPullDownListener(onPullDownListener);
		footView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onPullDownListener.onMore();
			}
		});

		videsList.setOnScrollListener(BitmapUtils.onScrollListener);
		videsList.setSmoothScrollbarEnabled(true);
		videsList.setScrollingCacheEnabled(true);

		new DownLaodData().execute("");
		return view;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		NewListInfo newInfo = null;
		if(Utils.netWorkInfoToast(getActivity())){
			return ;
		}
		newInfo = (NewListInfo) adapter.getItem(position);
		if (newInfo.newsType.equals(NewListInfo.NEWS_TYPE_NEWS)) {
			Main.news_detailIntent.putExtra("id",
					Integer.parseInt(newInfo.news_id));
			ViewLayout.setViewPre(true, "新闻详情", ViewLayout.TAB_TAG_NEWS_DETAIL,
					context.cparent);
		} else if (newInfo.newsType.equals("album")) {

			Bundle bundle = new Bundle();
			bundle.putSerializable(NewListInfo.NEWS_TYPE_ALBUM, newInfo);
			Main.album_detailIntent.putExtra(NewListInfo.NEWS_TYPE_ALBUM,
					bundle);
			ViewLayout.setViewPre(true, "图赏详情",
					ViewLayout.TAB_TAG_ALBUM_DETAIL, context.cparent);
		} else if (newInfo.newsType.equals(NewListInfo.NEWS_TYPE_VIDEO)) {
			Bundle bundle = new Bundle();
			bundle.putSerializable(NewListInfo.NEWS_TYPE_VIDEO, newInfo);
			Main.vedio_detailIntent.putExtra(NewListInfo.NEWS_TYPE_VIDEO,
					bundle);
			ViewLayout.setViewPre(true, "视频详情",
					ViewLayout.TAB_TAG_VEDEIO_DETAIL, context.cparent);
			// HttpUtils.browser(newInfo.v_source_url, context);
		} else {
			DebugTools.toast(context, "未知类型的新闻:" + newInfo.newsType);
		}

	}

	private class DownLaodData extends
			AsyncTask<String, String, List<NewListInfo>> {

		@Override
		protected List<NewListInfo> doInBackground(String... params) {
			// TODO Auto-generated method stub
			List<NewListInfo> news = null;
			try {
				if (isFirst) {
					news = newsCache.get(brand.brand_name);
					if (isRefresh || null == news || news.isEmpty()
							|| news.size() < 1) {
						time = TimeUtils.getSystemtTimeP();
						// news = context.getVideos(currentPage, per, brand);
						news = getVChannel(currentPage, per, brand);
					} else {
						currentPage = (adapter.getCount() % per == 0) ? adapter
								.getCount() / per : adapter.getCount() / per
								+ 1;
					}
					isFirst = false;
				} else {
					news = getVChannel(currentPage, per, brand);
					// news = context.getVideos(currentPage, per, brand);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return news;
		}

		@Override
		protected void onPostExecute(List<NewListInfo> result) {

			// processBar.clearAnimation();
			processBar.setVisibility(View.GONE);
			// Log.i( brand.brand_name, currentPage + "");
			if (result != null && !result.isEmpty()) {
				if (isRefresh) {
					adapter = new NewsAdapter(result, context);
					videsList.setAdapter(adapter);
					mPullDownView.enableAutoFetchMore(true, 1);
					// 诉它数据加载完毕;
					mPullDownView.notifyDidLoad();
					mPullDownView.notifyDidRefresh();
				} else {
					adapter.adddata(result);
					// 告诉它获取更多完毕
					mPullDownView.notifyDidMore();
				}
				currentPage++;
				footLoadingProgressBar.setVisibility(View.INVISIBLE);
				footLoadingseeMore.setText("查看更多");
				newsCache.put(brand.brand_name, adapter.getNews());
			} else {
				footLoadingProgressBar.setVisibility(View.INVISIBLE);
				footLoadingseeMore.setText("没有了");
			}

			videsList.setVisibility(View.VISIBLE);

			// 诉它数据加载完毕;
			// // 诉它数据加载完毕;
			mPullDownView.notifyDidLoad();
			// 告诉它获取更多完毕
			mPullDownView.notifyDidMore();
			mPullDownView.setVisibility(View.VISIBLE);

			super.onPostExecute(result);
		}

	}

	/**
	 * 获取指定分页视频信息
	 * 
	 * @param page
	 * @param per
	 * @return
	 * @throws IOException
	 */
	public List<NewListInfo> getVChannel(int currentPage, int per, Brand brand)
			throws Exception {
		// int btid = Integer.valueOf(brand.brand_id);
		ArrayList<NewListInfo> videos = null;
		String urlPath = HttpUtils.BASE_URI + "get-vchannel?page="
				+ currentPage + "&per=" + per + "&id=" + brand.brand_id
				+ "&downtime=" + time;
		String jsonString = HttpUtils.getJsonString(urlPath);
		Map<String, Object> m = GSonTools.getObjectMaps(jsonString);
		List<Map<String, Object>> list = (List<Map<String, Object>>) m
				.get("result");
		String next = (String) m.get("is_next");
		return JsonParserUtils.getVchannlList(list);
	}
}
